package com.om.base;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.ListModel;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.om.common.ConstantsUtil;
import com.om.common.MD5;
import com.om.pages.PageInfo;
/**
 * AbstractBean的通用工厂类
 * @author tangchuan
 *
 */
public abstract class BeanFactory<T> {

	/**
	 * 当前工厂绑定的AbstractBean对象
	 */
	public AbstractBean bean = null;
	
	protected boolean useLuceneQuery =false;
	/**
	 * 当前工厂使用的数据库连接对象
	 */
	public Connection connection = null;
	
	/**
	 * 查询时候返回的字段列表，多个字段之间用逗号分隔
	 */
	public String selectColumns=""; 

	/**
	 * 当前用来生成BeanFactory实例的类
	 */
	public static Class BeanFactoryClass = null;
	
	/**
	 * 查询时所有的分页信息
	 */
	public PageInfo page = null;
	
	/**
	 * 查询时使用的排序表达式
	 */
	public String orderBy = "";
	

	/**
	 * 用来缓存当前项目中所有的AbstractBean子类对应数据库中的字段类型信息
	 */
	public static Hashtable<String, Hashtable> ColumnTypeDirectory = new Hashtable();

	/**
	 * 用来缓存当前项目中所有的AbstractBean子类对应数据库中的表字段信息
	 */
	public static Hashtable<String, String[]> TableColumnDirectory = new Hashtable();

	/**
	 * 用来缓存当前项目中所有的AbstractBean子类对应数据库中的表字段信息
	 */
	public static Hashtable<String, Hashtable> ColumnTypeNameDirectory = new Hashtable();
	
	/**
	 * 当前工厂使用的连接管理器
	 */
	public static BaseConnectionManage ConnectionManage = null;

	/**
	 * 通过一个对象的Class加载并返回一个对象实例
	 * @param beanClass 指定的Class
	 * @return beanClass 的一个经过初始化的实例
	 */
	public static  <T> T LoadBean(Class<T> beanClass){
		T bean =  null;
		try{
			bean =  (T)Class.forName(beanClass.getName()).newInstance();
			//((AbstractBean)bean).initColumns();
			((AbstractBean)bean).init();
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return  Optional.ofNullable(bean).get();
	}
	
	public static  <T> T LoadBean(Class<T> beanClass,Connection con){
		T bean =  null;
		try{
			bean =  (T)Class.forName(beanClass.getName()).newInstance();
		
			((AbstractBean)bean).connection = con;
			((AbstractBean)bean).init();
			//((AbstractBean)bean).initColumns();
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return  Optional.ofNullable(bean).get();
	}
	
	public static  <T> T LoadBean(Class<T> beanClass,Object pkValue){
		T bean =  null;
		try{
			bean =  (T)Class.forName(beanClass.getName()).newInstance();
			((AbstractBean)bean).loadItem(pkValue);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return  Optional.ofNullable(bean).get();
	}
	

	
	

	
	/**
	 * 根据主键值加载一个指定的class的对象，包括结构和数据
	 * @param beanClass 需要加载的对象的类
	 * @param pkValue 用来加载数据的主键值
	 * @return beanClass类型的一个对象
	 */
/*	public static AbstractBean LoadBean(Class beanClass,Object pkValue){
		AbstractBean bean =  null;
		try{
			bean =  (AbstractBean) Class.forName(beanClass.getName()).newInstance();
			bean.initColumns();
			bean.loadItem(pkValue);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return bean;
	}*/
	/**
	 * 根据指定的className获取一个初始化过结构的对象仅有结构，没有数据
	 * @param className 需要加载的对象的类的名称
	 * @return 一个仅有结构没有数据的对象
	 */
	public static AbstractBean LoadBean(String className){
		AbstractBean bean =  null;
		try{
			bean =  (AbstractBean) Class.forName(className).newInstance();
			bean.init();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return bean;
	}
	
	/**
	 * 根据一个json字符串加载一个指定的class的对象，包括结构和数据
	 * @param className  要加载的对象的类的名称
	 * @param jsonObj 一个带有数据的json对象
	 * @return beanClass类型的一个对象
	 */
	public static AbstractBean LoadBean(String className,JSONObject jsonObj){
		AbstractBean bean =  null;
		try{
			bean =  (AbstractBean) Class.forName(className).newInstance();
			bean.init();
			bean.json2Model(jsonObj);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return bean;
	}
	
	
	/**
	 * 根据一个json对象填充一个指定的class的对象，包括结构和数据
	 * @param beanClass
	 * @param jsonString
	 * @return 一个通过jsonString 填充后的className类型的对象实例
	 */
	public static AbstractBean LoadBean(String className,String jsonString){
		AbstractBean bean =  null;
		try{
			bean =  (AbstractBean) Class.forName(className).newInstance();
			bean.initColumns();
			bean.json2Model(jsonString);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return bean;
	}
	
	/**
	 * 根据指定的类型创建一个BeanFactory对象
	 * @param modelClass 需要创建的BeanFactory的类
	 * @return  modelClass类型的BeanFactory的子类实例
	 */
	public static BeanFactory GenerateFactory(Class modelClass ) {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				factory.connection = Utils.GetOpenedConnection();
				AbstractBean bean =  (AbstractBean) Class.forName(modelClass.getName()).newInstance();
				factory.bean = bean;
				factory.InitColumns(bean, null);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}
	
	/**
	 * 根据指定的类型创建一个BeanFactory对象
	 * @param modelClass 需要创建的BeanFactory的类
	 * @param con 数据库对象
	 * @return modelClass类型的BeanFactory的子类实例
	 */
	public static BeanFactory GenerateFactory(Class modelClass, Connection con) {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				AbstractBean bean =  (AbstractBean) Class.forName(modelClass.getName()).newInstance();
				factory.connection = con;
				factory.bean = bean;
				factory.InitColumns(bean, con);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}
	
	/**
	 * 根据实体的类型创建一个BeanFactory对象
	 * @param bean 实体对象
	 * @return 一个BeanFactory的实例
	 */
	public static BeanFactory GenerateFactory(AbstractBean bean) {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				factory.connection = Utils.GetOpenedConnection();
				factory.bean = bean;
				factory.InitColumns(bean, null);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}
	
	
	public static BeanFactory GenerateFactory(Connection con) {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				if (con == null ){
					con =Utils.GetOpenedConnection();
				}
				factory.connection = con;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}

	
	public static BeanFactory GenerateFactory() {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				factory.connection = Utils.GetOpenedConnection();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}

	public static BeanFactory GenerateFactory(AbstractBean bean, Connection con) {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				factory.connection = con;
				factory.bean = bean;
				factory.InitColumns(bean, con);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}
	
	public static BeanFactory GenerateFactory(Class clasz,AbstractBean bean, Connection con) {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				factory.connection = con;
				factory.bean = bean;
				factory.InitColumns(bean, con);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}
	
	
	/**
	 * 根据实体的类型创建一个BeanFactory对象
	 * @param bean 实体类型
	 * @param con 数据库连接
	 * @param page 分页信息
	 * @return  一个BeanFactory的实例
	 */
	public static BeanFactory GenerateFactory(AbstractBean bean,
			Connection con, PageInfo page) {
		BeanFactory factory = null;
		try {
			if (BeanFactoryClass != null) {
				String className = BeanFactoryClass.getName();
				factory = (BeanFactory) Class.forName(className).newInstance();
				factory.page = page;
				factory.connection = con;
				factory.bean = bean;
				factory.InitColumns(bean, con);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return factory;
	}
	
	/**
	 * 通过原始的sql语句进行查询
	 * @param sql 需要执行查询的sql语句
	 * @param con 数据库连接
	 * @return 最原始的ResultSet对象（相当于数据库的游标）
	 */
	public static ResultSet QueryBySql(String sql, Connection con) {
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			if(con == null ){
				con = Utils.GetOpenedConnection();
			}
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			System.out.println(sql);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return rs;
	}
	
	/**
	 * 通过原始的sql语句进行查询
	 * @param sql 需要执行查询的sql语句
	 * @param con 数据库连接
	 * @return 最原始的ResultSet对象（相当于数据库的游标）
	 */
	public static ResultSet QueryBySql(String sql,SqlFilter filter, Connection con) {
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			if(con == null ){
				con = Utils.GetOpenedConnection();
			}
			String strExpress = filter.getFilterExpress();
			String spit  = strExpress.trim().equals("")?"":"where";
			if(sql.indexOf("${where}")!=-1){
				sql = sql.replace("${where}",spit+strExpress);
			}
			else {
				spit = sql.toLowerCase().indexOf("where")==-1?" where ":" And ";
				sql+=spit +strExpress;
			}
			pst = BeanFactory.GenerateFactory().prepareSql(sql, filter.getFieldList(), filter.getValueList());
			rs = pst.executeQuery();
			System.out.println(sql);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return rs;
	}
	
	
	/**
	 * 通过原始的sql语句获进行查询
	 * @param sql 需要查询的语句
	 * @return 符合查询条件的记录集合（DataRow类型的列表）
	 * @throws SQLException
	 */
	public static List<DataRow> QueryByNativeSql(String sql) throws Exception{
		return QueryByNativeSql(sql,null);
	}
	
	public static List<DataRow> QueryByNativeSql(String sql,SqlFilter filter,Connection con) throws Exception{
		
		List<DataRow> rows = new ArrayList<DataRow>();
		ResultSet rs = null;
		try {
			rs = BeanFactory.QueryBySql(sql,filter, con);
			while (rs.next()) {
				ResultSetMetaData met = rs.getMetaData();
				DataRow row = new DataRow();
				for (int i = 0; i < met.getColumnCount(); ++i) {
					String field = met.getColumnLabel(i + 1);
					row.set(field, rs.getObject(field));
				}
				rows.add(row);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		} finally {
			if (rs != null) {
				rs.close();
			}
		}
		return rows;
	}
	
	

	
	public static List<DataRow> QueryByNativeSql(String sql, Connection con) throws Exception {
		List<DataRow> rows = new ArrayList<DataRow>();
		ResultSet rs = null;
		try {
			rs = BeanFactory.QueryBySql(sql, con);
			while (rs.next()) {
				ResultSetMetaData met = rs.getMetaData();
				DataRow row = new DataRow();
				for (int i = 0; i < met.getColumnCount(); ++i) {
					String field = met.getColumnLabel(i + 1);
					row.set(field, rs.getObject(field));
				}
				rows.add(row);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		} finally {
			if (rs != null) {
				rs.close();
			}
		}
		return rows;
	}

	
	/**
	 * 执行原始的Sql语句
	 * @param sql 需要之行的sql语句
	 * @return 影响的记录数
	 * @throws SQLException
	 */
	public static int ExecuteQuery(String sql) throws SQLException {

		return ExecuteQuery(sql,null);
	}
	
	/**
	 * 执行原始的Sql语句
	 * @param sql sql 需要之行的sql语句
	 * @param connection 数据库连接
	 * @return 影响的记录数
	 * @throws SQLException
	 */
	@SuppressWarnings("finally")
	public static int ExecuteQuery(String sql, Connection connection)throws SQLException {
		
		PreparedStatement pst = null;
		int effectNum = 0;
		Connection con = null;
		try {
			if (connection != null) {
				con = connection;
			} else {
				con = Utils.GetOpenedConnection();
			}

			pst = con.prepareStatement(sql);
			effectNum = pst.executeUpdate();
			//System.out.println(sql);

		} catch (Exception ex) {
			System.out.println(sql);
			ex.printStackTrace();
			throw ex;
		} finally {
			if (pst != null) {
				pst.close();
			}
			return effectNum;
		}

	}
	
	/**
	 * 查询符合条件的第一条记录的第一个字段值
	 * @param sql 需要查询的sql语句
	 * @return  符合条件的第一条记录的第一个字段值
	 */
	public static Object QueryColumn(String sql) {
		return QueryColumn(sql,null);
	}
	
	public static Object QueryColumn(String sql, Connection connection) {
		PreparedStatement pst = null;
		Object obj = null;
		try {
			if(connection == null){
				connection = Utils.GetOpenedConnection();
			}
			pst = connection.prepareStatement(sql);
			ResultSet rsKey = pst.executeQuery();
			if (rsKey.next()) {
				obj = rsKey.getObject(1);
			}
			System.out.println(sql);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		finally{
			return obj;
		}

		
	}
	
	
	public static Object QueryColumn(String sql,SqlFilter filter, Connection connection) {
		PreparedStatement pst = null;
		Object obj = null;
		try {
			if(connection == null){
				connection = Utils.GetOpenedConnection();
			}
			//pst = connection.prepareStatement(sql);
			pst = BeanFactory.GenerateFactory().prepareSql(sql,filter.getFieldList(),filter.getValueList());
			ResultSet rsKey = pst.executeQuery();
			if (rsKey.next()) {
				obj = rsKey.getObject(1);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		finally{
			return obj;
		}

		
	}
	

   
	public static void ExecuteQuery(String sql, SqlFilter filter,Connection con) throws Exception {
		PreparedStatement pst = null;
		try {
			if(con == null ){
				con = Utils.GetOpenedConnection();
			}
			String strExpress = filter.getFilterExpress();
			String spit  = strExpress.trim().equals("")?"":"where";
			if(sql.indexOf("${where}")!=-1){
				sql = sql.replace("${where}",spit+strExpress);
			}
			else {
				spit = sql.toLowerCase().indexOf("where")==-1?" where ":" And ";
				sql+=spit +strExpress;
			}
			pst = BeanFactory.GenerateFactory().prepareSql(sql, filter.getFieldList(), filter.getValueList());
			pst.executeUpdate();
			System.out.println(sql);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
	}
	
	public static Object ExecuteQuery(String sql, SqlFilter filter,AbstractBean bean, Connection connection) throws Exception {
		PreparedStatement pst = null;
		BeanFactory factory = null;
		Object obj = null;
		try {
			if (filter == null)
				filter = new SqlFilter();
			factory = GenerateFactory(bean);
			factory.connection = connection;
			filter.getFilterExpress();
			List<String> fieldList = filter.getFieldList();
			bean.initColumns();
			for (int i = 0; i < fieldList.size(); i++) {
				String field = fieldList.get(i);
				Pattern p = Pattern.compile("(\\^\\d+)");
				Matcher m = p.matcher(field);
				if (m.find()) {
					field = m.replaceAll("");
				}
				if (!bean.containsColumn(field)) {
					//filter.remove(fieldList.get(i));
				}
			}
			
			Pattern p = Pattern.compile("(\\$|@)\\{\\w+\\}");
			Matcher m = p.matcher(sql);
			String strExpress = filter.getFilterExpress();
			if(m.find()){
				/**
				 *自己手动重载了generateQuerySql且其中已经带有了where和各种参数占位符
				 *按照Sql语句中占位符的顺序对SqlFilter立面的各项做调整 
				 */
				String field = m.group(); 
				String field1 = field.replaceAll("(\\$|@)", "").replace("}", "").replace("{", "");
				String value = filter.getValue(field1).toString();
				sql = sql.replaceAll("\\$\\{"+field1+"\\}" , value);
				while(m.find()){
					field = m.group(); 
					field1 = field.replaceAll("(\\$|@)", "").replace("}", "").replace("{", "");
					value = filter.getValue(field1).toString();
					sql = sql.replaceAll("\\$\\{"+field1+"\\}" , value);
				}
				pst = factory.prepareSql(sql, new ArrayList(),new ArrayList());
			}
			else if(sql.indexOf("${where}")==-1 && sql.indexOf("where")==-1 &&  sql.indexOf("CALL")==-1 &&  !"".equals(strExpress)){//调用存储过程或者是带了${where}占位符
				sql = sql + " where " + strExpress;
			}
			else//默认的情况
			{
				sql = sql.replace("${where}", " where " + strExpress);
			}
			if(pst==null){
				pst = factory.prepareSql(sql, filter.getFieldList(),filter.getValueList());
			}
			
			ResultSet rsKey = pst.executeQuery();
			if (rsKey.next()) {
				obj = rsKey.getObject(1);
			}
			

		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}

		return obj;
	}
	
	/**
	 * 根据查询条件获取一个指定实体对象的记录条数
	 * @param filter 过滤条件
	 * @param bean 实体对象
	 * @param connection 数据库连接
	 * @return 返回符合filter条件的记录数
	 * @throws Exception 
	 */
	public static int GetRecordCount(SqlFilter filter, AbstractBean bean,Connection connection) throws Exception {
		int count = 0;

		//String sql = bean.generateCountSql();
		String sql = bean.generateCountSql(filter);
		Object obj = ExecuteQuery(sql, filter, bean, connection);
		if (obj != null) {
			count = Integer.valueOf(obj.toString()).intValue();
		}
		return count;
	}
	
	/**
	 * 返回符合过滤条件的记录数字
	 * @param filter 过滤条件
	 * @return 符合过滤条件的记录数字
	 * @throws Exception 
	 */
	public  int getRecordCount(SqlFilter filter) throws Exception {
		int count = 0;
		SqlFilter filterClone = filter.clone();
		filterClone.attachCondition="";
		if (LuceneUtils.IndexExist(this.bean.LuceneIndexClass) && !filterClone.getFilterExpress().equals("") && "".equals(filter.attachCondition.trim())) {
			LuceneUtils lu = new LuceneUtils(this.bean.LuceneIndexClass);
			return lu.getMatchCount(filter);
		}
		String sql = bean.generateCountSql(filter);
		count = getRecordCount(sql,filter);
		return count;
	}

	
	/**
	 * 返回符合过滤条件的记录数字
	 * @param sql 查询语句
	 * @param filter 过滤条件
	 * @return 回符合过滤条件的记录数字
	 * @throws Exception 
	 */
	public  int getRecordCount(String sql ,SqlFilter filter) throws Exception {
		int count = 0;
		if(sql.indexOf("CALL")==-1){
			AdjustFilter(filter);
		}
		Object obj = ExecuteQuery(sql, filter, bean, connection);
		if (obj != null) {
			count = Integer.valueOf(obj.toString()).intValue();
		}
		return count;
	}
	
	public void InitColumns(AbstractBean bean, Connection conn)
			throws Exception {
		Connection con = null;
		Statement pst = null;
		ResultSet rs = null;

		if (bean.Field.length > 0)
			return;

		try {
			String tableName=bean.TABLE_NAME;
			if(tableName.equals("")){
				tableName = MD5.MD5Encode(bean.generateQuerySql());
			}
			if (TableColumnDirectory.containsKey(tableName)) {
				String[] columns = (String[]) TableColumnDirectory
						.get(tableName);
				if(columns!=null){
					bean.Field = new String[columns.length];
				}
				
				int i = 0;
				while (true) {
					bean.Field[i] = columns[i];

					++i;
					if (i >= columns.length) {
						label79: return;
					}
				}
			}

			//if (!bean.TABLE_NAME.equals("")) {
				
				
				if (conn != null) {
					con = conn;
				} else {
					con = Utils.GetOpenedConnection();
				}

				
				
				String sql = bean.getEmptySql();
				if(sql!=null && !"".equals(sql)){
					Hashtable map = new Hashtable();
					pst = con.createStatement();
					rs = pst.executeQuery(sql);
					ResultSetMetaData met = rs.getMetaData();
					int length = met.getColumnCount();
					bean.Field = new String[length];
					for (int i = 0; i < length; ++i) {
						String column = met.getColumnLabel(i + 1);
						String typeName = met.getColumnTypeName(i + 1);
						bean.Field[i] = column;
						map.put(column, typeName);
					}
					
					ColumnTypeNameDirectory.put(tableName, map);
				    TableColumnDirectory.put(tableName,(String[]) bean.Field.clone());
				}
			//}
			

		} catch (Exception ex) {
			Utils.WriteLog(ex.getMessage() + "\r\n" + ex.getStackTrace());
			ex.printStackTrace();
			throw ex;
		}

	}
	
	/**
	 * 根据指定的对象类型查询符合条件的对象列表
	 * @param beanClass 需要进行查询的对象的Class 
	 * @param filter 包含查询条件的SqlFilter對象
	 * @param selectColumns 需要显示的字段列表，如果有多个用逗号分隔，如果该值为null则显示所有字段
	 * @return 符合查询条件的beanClass类型的对象列表 
	 * @throws Exception 
	 */
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,
			SqlFilter filter,String selectColumns) throws Exception {
		return BeanFactory.GetBeanList(beanClass, filter, selectColumns,Utils.GetOpenedConnection());
	}
	
	/**
	 * 根据指定的对象类型查询符合条件的对象列表
	 * @param beanClass 需要进行查询的对象的Class
	 * @param filter 包含查询条件的SqlFilter對象
	 * @param loadChild 是否在查詢結束后自動加載對應記錄的子表數據
	 * @return 符合查询条件的beanClass类型的对象列
	 * @throws Exception
	 */
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,
			SqlFilter filter,boolean loadChild) throws Exception {
		ArrayList<AbstractBean> beanList = BeanFactory.GetBeanList(beanClass, filter, null,Utils.GetOpenedConnection());
		if(loadChild){
			for(int i=0;i<beanList.size();i++){
				beanList.get(i).loadAllChildren();
			}
		}
		return beanList;
	}
	
	
	/**
	 * 根据制定的对象类型查询符合条件的对象列表
	 * @param beanClass 需要进行查询的对象的Class 
	 * @param filter 查询条件
	 * @param orderBy 排序规则 order by ....
	 * @param selectColumns 需要显示的字段列表，如果有多个用逗号分隔，如果该值为null则显示所有字段
	 * @return 符合查询条件的beanClass类型的对象列表 
	 * @throws Exception 
	 */
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,
			SqlFilter filter,String orderBy,String selectColumns) throws Exception {
		return BeanFactory.GetBeanList(beanClass, filter,orderBy, selectColumns,Utils.GetOpenedConnection());
	}
	
	/**
	 * 根据制定的对象类型查询符合条件的对象列表
	 * @param beanClass 需要进行查询的对象的Class 
	 * @param filter filter 查询条件
	 * @param selectColumns 需要显示的字段列表，如果有多个用逗号分隔，如果该值为null则显示所有字段
	 * @param orderBy 排序规则 order by ....
	 * @param con 数据库连接（如果该参数为空框架会调用默认的数据库连接）
	 * @return 符合查询条件的beanClass类型的对象列表 
	 * @throws Exception 
	 */
	public  static <T> List<T> GetBeanList(Class<T> beanClass){
		
		List<T> beanList = new ArrayList<T>();
		return beanList ;
	}
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,
			SqlFilter filter,String orderBy,String selectColumns, Connection con) throws Exception {
		
		BeanFactory factory = null;
		ArrayList beanList = new ArrayList();
		PreparedStatement pst = null;
		CallableStatement call=null;
		ResultSet rs = null;
		
		try {
			if (filter == null) {
				filter = new SqlFilter();
			}
			String className = beanClass.getName();
			AbstractBean bean = (AbstractBean) Class.forName(className).newInstance();
			
			if(con == null){
				con = Utils.GetOpenedConnection();
			}
			bean.connection = con;
			bean.init();
			if(orderBy!=null && !"".equals(orderBy)){
				bean.setDefaultOrderByExpress(orderBy);
				Pattern p0 = Pattern.compile("limit\\s+\\d+");
				Matcher m0 = p0.matcher(orderBy.toLowerCase());
				if (m0.find()) {
					Matcher m01 = Pattern.compile("\\d+").matcher(m0.group());
					if(m01.find()){
						bean.setDefaultPageSize(Integer.parseInt(m01.group()));
					}
					
				}
			}
			
			String sql = bean.generateQuerySql(filter);
			if(selectColumns!=null && !"".equals(selectColumns)){
				sql = sql.replace("*", selectColumns);
			}
			
			
			
			
			factory = GenerateFactory(bean, con);
			if(orderBy!=null && !"".equals(orderBy)){
				Pattern p1 = Pattern.compile("order\\s+by");
				Matcher m1 = p1.matcher(sql.toLowerCase());
				if (orderBy != null && !m1.find()) {
					sql += orderBy;
				}
				else{
					sql.replaceAll("order\\s+by", orderBy);
				}
			}
			
			if(sql.indexOf("CALL")!=-1){
				call = factory.prepareCallableStatement(sql, filter);
				rs = call.executeQuery();
			}
			else {
				pst = factory.prepareSql(sql, filter.getFieldList(), filter.getValueList());
				rs = pst.executeQuery();
			}
			

			ResultSetMetaData met = rs.getMetaData();
			while (rs.next()) {
				AbstractBean item = (AbstractBean) Class.forName(className).newInstance();
				if (item.Field.length == 0) {
					item.Field = new String[met.getColumnCount()];
					for (int i = 0; i < met.getColumnCount(); ++i) {
						String column = met.getColumnLabel(i + 1);
						item.Field[i] = column;
					}
				}
				
				item.TABLE_NAME = bean.TABLE_NAME;
				item.PrimaryKey = bean.PrimaryKey;
				item.PrimaryKeyField = bean.PrimaryKeyField;
				item.requireList = bean.requireList;
				item.uniqueList = bean.uniqueList;
				item.readonlyList = bean.readonlyList;
				item.childMap = bean.childMap;
				item.forignMap = bean.forignMap;
				
				
				Pattern p = Pattern.compile("\\d{4}-\\d{1,2}-\\d{1,2}\\s+\\d{1,2}:\\d{1,2}:\\d{1,2}");
				for (int i = 0; i < item.Field.length; ++i) {
					try {
						Object value = null;
						String columnName = item.Field[i];
						String columnTypeName = met.getColumnTypeName(i + 1);
						if (columnTypeName.indexOf("BLOB") != -1) {
							value = rs.getAsciiStream(columnName);
						} else if (columnTypeName.indexOf("TINYINT") != -1) {
							value = rs.getShort(columnName);
						}
						else if(columnTypeName.toLowerCase().indexOf("datetime")!=-1){
							value = rs.getObject(columnName);
							if(value!=null){
								Matcher match = p.matcher(value+"");
								if (match.find()) {
									value = match.group(0);
								}
							}
							
							
						} else {
							value = rs.getObject(columnName);
						}
						item.set(columnName, value);
					} catch (Exception localException1) {
					}
				}
				item.set(AbstractBean.KEY_VALUE, item.getKeyValue());
				item.afterLoad();
				beanList.add(item);
				
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
			try {
				if(pst!=null && !pst.isClosed()){
					pst.close();
				}
				if(call!=null && !call.isClosed()){
					call.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}
			
			return beanList;
		}
	/**
	 * 根据指定的对象类型查询符合条件的对象列表
	 * @param beanClass beanClass 需要进行查询的对象的Class 
	 * @param filter filter 查询条件
	 * @param selectColumns selectColumns 需要显示的字段列表，如果有多个用逗号分隔，如果该值为null则显示所有字段
	 * @param con 数据库连接
	 * @return 符合查询条件的beanClass类型的对象列表 
	 * @throws Exception 
	 */
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,
			SqlFilter filter,String selectColumns, Connection con) throws Exception {
		return GetBeanList(beanClass,filter,null,selectColumns,con);
	}

	
	/**
	 * json字符串填充指定的对象类型查询符合条件的对象列表
	 * @param beanClass  需要进行填充的对象的Class 
	 * @param strJson  与beanClass具有相似结构的json字符串
	 * @param con 数据库连接
	 * @return beanClass类型的对象列表 
	 * @throws Exception 
	 */
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,String strJson,Connection con) throws Exception{
		ArrayList<AbstractBean> list = new ArrayList<AbstractBean>();
		try{
			AbstractBean bean = (AbstractBean) Class.forName(
					beanClass.getName()).newInstance();
			
		   if(con == null ){
			   con = Utils.GetOpenedConnection();
		   }
			bean.connection = con;
			bean.init();


            //JSONObject jsonObj = (JSONObject) JSONObject.fromObject(strJson);
            JSONArray jsons = JSONArray.fromObject(strJson);
            for (int i = 0; i < jsons.size(); i++) {
				JSONObject tempJson = JSONObject.fromObject(jsons.get(i));
				AbstractBean item = (AbstractBean) Class.forName(beanClass.getName()).newInstance();
				item.Field = bean.Field;
				item.TABLE_NAME = bean.TABLE_NAME;
				item.PrimaryKey = bean.PrimaryKey;
				item.PrimaryKeyField = bean.PrimaryKeyField;
				item.requireList = bean.requireList;
				item.uniqueList = bean.uniqueList;
				item.readonlyList = bean.readonlyList;
				item.childMap = bean.childMap;
				item.forignMap = bean.forignMap;
				
				Object [] keys = tempJson.keySet().toArray();
				
				for (int j = 0; j < keys.length; j++) {
					String field = keys[j].toString();
					item.set(field, tempJson.get(field));
				}
				item.set(AbstractBean.KEY_VALUE, item.getKeyValue());
				item.afterLoad();
				list.add(item);
			}

		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
		return list;
	}
	
	/**
	 * 
	 * @param beanClass 需要进行填充的对象的Class
	 * @param jsons  beanClass具有相似结构的json字符串
	 * @param con 数据库连接 
	 * @return beanClass类型的对象列表 
	 * @throws Exception 
	 */
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,JSONArray jsons, Connection con) throws Exception {
		ArrayList<AbstractBean> list = new ArrayList<AbstractBean>();
		try {
			AbstractBean bean = (AbstractBean) Class.forName(beanClass.getName()).newInstance();
			
			if (con == null) {
				con = Utils.GetOpenedConnection();
			}
			bean.connection = con;
			bean.init();
			for (int i = 0; i < jsons.size(); i++) {
				JSONObject tempJson = JSONObject.fromObject(jsons.get(i));
				AbstractBean item = (AbstractBean) Class.forName(beanClass.getName()).newInstance();
				item.Field = bean.Field;
				item.TABLE_NAME = bean.TABLE_NAME;
				item.PrimaryKey = bean.PrimaryKey;
				item.PrimaryKeyField = bean.PrimaryKeyField;
				item.requireList = bean.requireList;
				item.uniqueList = bean.uniqueList;
				item.readonlyList = bean.readonlyList;
				item.childMap = bean.childMap;
				item.forignMap = bean.forignMap;
				
				item.json2Model(tempJson);
				item.set(AbstractBean.KEY_VALUE, item.getKeyValue());
				item.afterLoad();
				list.add(item);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		return list;
	}
	
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,JSONArray jsons) throws Exception {
		ArrayList<AbstractBean> list = new ArrayList<AbstractBean>();
		try {
			AbstractBean bean = (AbstractBean) Class.forName(beanClass.getName()).newInstance();
			
			bean.connection = Utils.GetOpenedConnection();
			bean.init();
			for (int i = 0; i < jsons.size(); i++) {
				JSONObject tempJson = JSONObject.fromObject(jsons.get(i));
				AbstractBean item = (AbstractBean) Class.forName(beanClass.getName()).newInstance();
				item.Field = bean.Field;
				item.TABLE_NAME = bean.TABLE_NAME;
				item.PrimaryKey = bean.PrimaryKey;
				item.PrimaryKeyField = bean.PrimaryKeyField;
				item.requireList = bean.requireList;
				item.uniqueList = bean.uniqueList;
				item.readonlyList = bean.readonlyList;
				item.childMap = bean.childMap;
				item.forignMap = bean.forignMap;
				
				
				item.json2Model(tempJson);
				item.set(AbstractBean.KEY_VALUE, item.getKeyValue());
				item.afterLoad();
				list.add(item);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		return list;
	}
	
	
	/**
	 * json字符串填充指定的对象类型查询符合条件的对象列表
	 * @param beanClass  需要进行查询的对象的Class 
	 * @param strJson   与beanClass具有相似结构的json字符串
	 * @return beanClass类型的对象列表 
	 */
	public static ArrayList<AbstractBean> GetBeanList(Class beanClass,String strJson){
		ArrayList<AbstractBean> list = new ArrayList<AbstractBean>();
		try{
			AbstractBean bean = (AbstractBean) Class.forName(beanClass.getName()).newInstance();
		   	bean.connection = Utils.GetOpenedConnection();
			bean.init();
            //JSONObject jsonObj = (JSONObject) JSONObject.fromObject(strJson);
            //JSONArray jsons = jsonObj.getJSONArray(bean.getClassName());
            JSONArray jsons = JSONArray.fromObject(strJson);
            
			for (int i = 0; i < jsons.size(); i++) {
				JSONObject tempJson = JSONObject.fromObject(jsons.get(i));
				AbstractBean item = (AbstractBean) Class.forName(beanClass.getName()).newInstance();
				
				item.Field = bean.Field;
				item.TABLE_NAME = bean.TABLE_NAME;
				item.PrimaryKey = bean.PrimaryKey;
				item.PrimaryKeyField = bean.PrimaryKeyField;
				item.requireList = bean.requireList;
				item.uniqueList = bean.uniqueList;
				item.readonlyList = bean.readonlyList;
				item.childMap = bean.childMap;
				item.forignMap = bean.forignMap;
				
				item.json2Model(tempJson);
				item.set(AbstractBean.KEY_VALUE, item.getKeyValue());
				item.afterLoad();
				list.add(item);
			}

		}catch(Exception ex){
			ex.printStackTrace();
		}
		return list;
	}

	
	
	
	public void AdjustFilter(SqlFilter filter) {

		Hashtable typeMap = getFieldType();
		List list = filter.getFieldList();
		Pattern p = Pattern.compile("\\d{4}(/|-)\\d{1,2}(/|-)\\d{1,2}");
		for (int i = 0; i < list.size(); ++i) {
			String field = (String) list.get(i);
			String fieldReal = field;
			Pattern p2 = Pattern.compile("(\\^\\d+)");
			Matcher m2 = p2.matcher(fieldReal);
			if (m2.find()) {
				fieldReal = m2.replaceAll("");
			}
			Object value = filter.getValue(field);
			String op = filter.getOperation(field).toLowerCase().trim();
			Matcher m = p.matcher(value + "");
			if (value == null)
				continue;
			//if (typeMap.containsKey(fieldReal)) {
				if ("like".equals(op)) {
					int type = ((Integer) typeMap.get(field)).intValue();
					if ((type == 1) || (type == 12) || (type == -9)
							|| (type == 12))
						continue;
					String adValue = value.toString().replace("%", "");
					filter.setOperation(field, "=");
					filter.setValue(field, adValue);
				} else if (m.find()) {
					if (">=".equals(op)) {
						value = value + " 00:00:00";
					} else if ("<=".equals(op)) {
						value = value + " 23:59:59";
					}
					filter.setValue(field, value);
				}

			//}
		}
	}
	
	/**
	 * 根据查询条件和分页信息检查询对象列表
	 * @param filter 过滤条件
	 * @param pageInfo 分页信息
	 * @return 指定类型的对象列表
	 */
	public  ArrayList<AbstractBean> getBeanList(SqlFilter filter, PageInfo pageInfo){
		ArrayList<AbstractBean>beanList = new ArrayList<AbstractBean>();
		if(this.bean!=null){
			beanList = this.getBeanList(this.bean.getClass(), filter, pageInfo);
		}
		return beanList;
		
	}
	
	
	/**
	 * 根据指定的对象类型查询符合过滤条件和分页信息检查询对象列表
	 * @param beanClass 需要进行检索的对象Class
	 * @param filter 过滤条件
	 * @param page 分页信息
	 * @return 指定类型的对象列表
	 */
	public abstract ArrayList<AbstractBean> getBeanList(Class<?> beanClass,
			SqlFilter filter, PageInfo page);
	
	/**
	 * 根据查询条件和记录的开始索引，结束索引检查询对象列表
	 * @param filter 过滤条件
	 * @param startIndex 记录的开始索引
	 * @param endIndex 记录的结束索引
	 * @return 指定类型的对象列表
	 */
	public ArrayList<AbstractBean> getBeanList(SqlFilter filter,
			int startIndex, int endIndex) {
		ArrayList<AbstractBean> beanList = new ArrayList<AbstractBean>();
		if (this.bean != null) {
			beanList = this.getBeanList(this.bean.getClass(), filter,
					startIndex, endIndex);
		}
		return beanList;
	}
	
	/**
	 * 根据指定的对象类型查询条件和记录的开始索引，结束索引检查询对象列表
	 * @param beanClass 需要进行检索的对象类型
	 * @param filter 过滤条件
	 * @param startIndex 记录的开始索引
	 * @param endIndex 记录的结束索引
	 * @return 指定类型的对象列表
	 */
	public abstract ArrayList<AbstractBean> getBeanList(Class<?> beanClass,
			SqlFilter filter, int startIndex, int endIndex);
	
	/**
	 * 根据过滤条件和排序字段列表返回查询结果
	 * @param filter 过滤条件
	 * @param orderBy 排序字段列表，多个字段间用逗号分隔
	 * @return 指定类型的对象列表
	 */
	public abstract ArrayList<AbstractBean> getBeanList(
			SqlFilter filter, String orderBy);
	
	/**
	 * 为指定的sql语句创建相应的PreparedStatement对象
	 * @param sql 带有参数占位符的sql语句
	 * @param lstField  占位符对应的字段列表
	 * @param lstValue  与占位符对应的字段值
	 * @return 按照占位符字段和占位符值替换过的PreparedStatement对象
	 * @throws Exception 
	 */
	public PreparedStatement prepareSql(String sql, List<String> lstField,List<?> lstValue) throws Exception {
		PreparedStatement pst = null;

		Map<String, String> sqlparamHashtable = new LinkedHashMap<String, String>();
		SqlFilter ftParamSql =new SqlFilter();
		String columnTypeName = "";
		String field ="";
		try {
			Hashtable<String, Integer> typeMap = getFieldType();
			Hashtable<String, String> columnTypeMap = getColumnTypeNames();
			pst = this.connection.prepareStatement(sql);
			if (lstField != null && lstValue != null) {
				for (int i = 0; i < lstField.size(); ++i) {
					field = (String) lstField.get(i).replace("`", "");

					if (lstValue.size() > i) {
						Pattern p = Pattern.compile("(\\^\\d+)");
						Matcher m = p.matcher(field);

						if (m.find()) {
							field = m.replaceAll("");
						}

						p = Pattern.compile("(\\w+\\.)");
						m = p.matcher(field);
						if (m.find()) {
							field = m.replaceAll("");
						}

						Object value = lstValue.get(i);
						if (value != null) {
							sqlparamHashtable.put(field, value.toString());
							ftParamSql.addFilter(field, SqlFilter.OP.EQUALS, value);
						} else {
							sqlparamHashtable.put(field, "null");
							ftParamSql.addFilter(field, SqlFilter.OP.EQUALS, "null");
						}

						

						Integer sqlType = (Integer) typeMap.get(field);
						if (sqlType == null) {
							sqlType = Integer.valueOf(12);
						}
						if (columnTypeMap.containsKey(field)) {
							columnTypeName = (String) columnTypeMap.get(field);
						}

						if (value == null) {
							pst.setNull(i + 1, sqlType);
						} else if (columnTypeName.indexOf("TINYINT") != -1) {
							pst.setShort(i + 1,
									Short.parseShort(value.toString()));
						} else {
							pst.setObject(i + 1, value, sqlType, 4);
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		getSqlInfo(sql, sqlparamHashtable);
		return pst;
	}
	
	public void prepareSql(String sql, List<String> lstField,List<?> lstValue,PreparedStatement pst) throws Exception {

		Map<String, String> sqlparamHashtable = new LinkedHashMap<String, String>();
		SqlFilter ftParamSql =new SqlFilter();
		String columnTypeName = "";
		String field ="";
		try {
			Hashtable<String, Integer> typeMap = getFieldType();
			Hashtable<String, String> columnTypeMap = getColumnTypeNames();
			
			
			if (lstField != null && lstValue != null) {
				for (int i = 0; i < lstField.size(); ++i) {
					field = (String) lstField.get(i).replace("`", "");

					if (lstValue.size() > i) {
						Pattern p = Pattern.compile("(\\^\\d+)");
						Matcher m = p.matcher(field);

						if (m.find()) {
							field = m.replaceAll("");
						}

						p = Pattern.compile("(\\w+\\.)");
						m = p.matcher(field);
						if (m.find()) {
							field = m.replaceAll("");
						}

						Object value = lstValue.get(i);
						if (value != null) {
							sqlparamHashtable.put(field, value.toString());
							ftParamSql.addFilter(field, SqlFilter.OP.EQUALS, value);
						} else {
							sqlparamHashtable.put(field, "null");
							ftParamSql.addFilter(field, SqlFilter.OP.EQUALS, "null");
						}

						

						Integer sqlType = (Integer) typeMap.get(field);
						if (sqlType == null) {
							sqlType = Integer.valueOf(12);
						}
						if (columnTypeMap.containsKey(field)) {
							columnTypeName = (String) columnTypeMap.get(field);
						}
						
						if (value == null) {
							pst.setNull(i + 1, sqlType);
						}
						else if("".equals(value) && (columnTypeName.toLowerCase().indexOf("char")==-1 && columnTypeName.toLowerCase().indexOf("text")==-1)){
							pst.setNull(i + 1, sqlType);
						}
						else if (columnTypeName.indexOf("TINYINT") != -1) {
							pst.setShort(i + 1,Short.parseShort(value.toString()));
						} else {
							pst.setObject(i + 1, value, sqlType, 4);
						}
						
					}
				}
			}
			pst.addBatch();
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		//getSqlInfo(sql, sqlparamHashtable);
	}

	
	/**
	 * 为指定的sql语句创建相应的PreparedStatement对象
	 * @param sql 带有参数占位符的sql语句
	 * @param lstField  占位符对应的字段列表
	 * @param lstValue 与占位符对应的字段值 
	 * @param autoGenerateKey 是否返回自增长ID
	 * @return 按照占位符字段和占位符值替换过的PreparedStatement对象
	 * @throws Exception 
	 */
	public PreparedStatement prepareSql(String sql, List<String> lstField,
			List<?> lstValue, int autoGenerateKey) throws Exception {
		PreparedStatement pst = null;
		Map<String, String> sqlparamHashtable = new LinkedHashMap<String, String>();
		SqlFilter ftParamSql = new SqlFilter();
		try {
			try {
				Hashtable<?, ?> typeMap = getFieldType();
				Hashtable<?, ?> columnTypeMap = getColumnTypeNames();
				Object value =null;
				String field="";
				pst = this.connection.prepareStatement(sql, autoGenerateKey);
				for (int i = 0; i < lstField.size(); ++i) {
					field = (String) lstField.get(i).replace("`", "");
					Pattern p = Pattern.compile("(\\^\\d+)");
					Matcher m = p.matcher(field);
					if (m.find()) {
						field = m.replaceAll("");
					}

					p = Pattern.compile("(\\w+\\.)");
					m = p.matcher(field);
					if (m.find()) {
						field = m.replaceAll("");
					}

					value = lstValue.get(i);
					if (value != null) {
						sqlparamHashtable.put(field, value.toString());
						ftParamSql.addFilter(field, SqlFilter.OP.EQUALS,value);
					}

					String columnTypeName = (String) columnTypeMap.get(field);

					Integer sqlType = (Integer) typeMap.get(field);
					if (value == null) {

						pst.setNull(i + 1, sqlType);
					} else if (columnTypeName.indexOf("TINYINT") != -1) {
						pst.setShort(i + 1, Short.parseShort(value.toString()));
					} else {
						pst.setObject(i + 1, value, sqlType, 4);
						// pst.setObject(i + 1, value);
					}
				}

			} catch (Exception ex) {
				ex.printStackTrace();
				throw ex;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		getSqlInfo(sql,sqlparamHashtable);
		return pst;
	}
	
	/**
	 * 根据存储过程名称和参数列表返回一个可执行的CallableStatement对象
	 * @param  procName 存储过程名称 
	 * @param  filter 带有存储过程参数值的SqlFilter对象
	 * @return 可执行的CallableStatement对象
	 * @throws Exception 
	 */
	public CallableStatement prepareCallableStatement(String procName, SqlFilter filter) throws Exception {
		CallableStatement pst = null;

		Map<String, String> sqlparamHashtable = new LinkedHashMap<String, String>();

		String paramsPattern = "(\\$|@)\\w+";
		if(this.connection == null){
			this.connection = Utils.GetOpenedConnection();
		}
		Pattern p = Pattern.compile(paramsPattern);
		Matcher m = p.matcher(procName);
		String sql2 = procName.replaceAll(paramsPattern, "?");
		pst = this.connection.prepareCall(sql2);
		int index=0;			
		while(m.find()){
			++index;
			String field = m.group(0); 
			field = field.replaceAll("(\\$|@)", "");
			pst.setObject(index, filter.getValue(field));
		}
		
		return pst;
	}
	
	
	private String getSqlInfo(String sql, Map<String, String> sqlparamHashtable) {
		
		if (!ConstantsUtil.isdebug)
			return "";
		int paramNum = 0;
		if (sqlparamHashtable.size() < 0) {
			System.out.println(sql);
			return sql;
		} else {
			StringBuffer returnSQL = new StringBuffer();
			String[] subSQL = sql.split("\\?");
			Set<String> keys = sqlparamHashtable.keySet();
			int i = 0;
			for (Iterator<?> it = keys.iterator(); it.hasNext(); i++) {
				String keyTemp = (String) it.next(); // name
				String valueString = (String) sqlparamHashtable.get(keyTemp);
				returnSQL.append(subSQL[i]).append(" '").append(valueString).append("' ");
			}
			if (subSQL.length > i) {
				returnSQL.append(subSQL[subSQL.length - 1]);
			}
			System.out.println(returnSQL.toString());
			return returnSQL.toString();
		}

		

	}

	
	/*private String getSqlInfo(String sql, SqlFilter filter) {
		
		List<String> fields = filter.Fields;

		if (filter.size() < 0) {
			System.out.println(sql);
			return sql;
		} else {
			StringBuffer returnSQL = new StringBuffer();
			String[] subSQL = sql.split("\\?");
			int index = 0;
			for(int i=0;i<fields.size();i++){
				String field = fields.get(i);
				Object value = filter.getValue(field);
				Pattern p = Pattern.compile("(\\^\\d+)");
				Matcher m = p.matcher(field);
				if (m.find()) {
					field = m.replaceAll("");
				}
				if(value!=null){
					returnSQL.append(subSQL[i]).append(" '").append(value).append("' ");
				}
				else{
					returnSQL.append(subSQL[i]).append(" null ");
				}
				index++;
				
			}
			if (subSQL.length > index) {
				returnSQL.append(subSQL[subSQL.length - 1]);
			}
			System.out.println(returnSQL.toString());
			return returnSQL.toString();
		}

		// 1 濡傛灉娌℃湁鍙傛暟锛岃鏄庢槸涓嶆槸鍔ㄦ�SQL璇彞

	}
	*/
	
	protected Hashtable<String, Integer> getFieldType() {
		Statement pst = null;
		ResultSet rs = null;
		Hashtable<String, Integer> typeMap = new Hashtable<String, Integer>();

		String sql = "";
		try {
			if(bean == null ) 
				return typeMap;
			if (ColumnTypeDirectory.containsKey(this.bean.TABLE_NAME)) {
				typeMap = (Hashtable<String, Integer>) ColumnTypeDirectory.get(this.bean.TABLE_NAME);
				return typeMap;
			}
			// sql = "select * from " + this.bean.TABLE_NAME + "  where 1=0";
			sql = bean.getEmptySql();
			pst = this.connection.createStatement();
			rs = pst.executeQuery(sql);
			ResultSetMetaData met = rs.getMetaData();

			for (int i = 0; i < met.getColumnCount(); ++i) {
				String column = met.getColumnName(i + 1);
				int type = met.getColumnType(i + 1);
				typeMap.put(column, new Integer(type));
			}
			ColumnTypeDirectory.put(this.bean.TABLE_NAME, typeMap);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (pst != null)
					pst.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return typeMap;
	}

	protected Hashtable<String, String> getColumnTypeNames() {
		Statement pst = null;
		ResultSet rs = null;
		Hashtable<String, String> map = new Hashtable<String, String>();

		String sql = "";
		try {
			if (this.bean == null || "".equals(this.bean.TABLE_NAME)) {
				return map;
			}

			if (ColumnTypeNameDirectory.containsKey(this.bean.TABLE_NAME)) {
				map = (Hashtable<String, String>) ColumnTypeNameDirectory.get(this.bean.TABLE_NAME);
				return map;
			}

			// sql = "select * from " + this.bean.TABLE_NAME + "  where 1=0";
			sql = bean.getEmptySql();
			pst = this.connection.createStatement();
			rs = pst.executeQuery(sql);
			ResultSetMetaData met = rs.getMetaData();

			for (int i = 0; i < met.getColumnCount(); ++i) {
				String column = met.getColumnName(i + 1);
				String typeName = met.getColumnTypeName(i + 1);
				map.put(column, typeName);
			}
			ColumnTypeNameDirectory.put(this.bean.TABLE_NAME, map);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (pst != null)
					pst.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	
	/**
	 * 对指定表的某个字段做唯一性验证
	 * @param beanClass 需要检查的对象的Class
	 * @param field 需要检查的字段名称
	 * @param value 需要检查的字段的值
	 * @param keyValue 需要验证的记录的主键值
	 * @return 成功返回true否则返回false
	 */
	public static boolean UniqueValidate(Class beanClass, String field,
			Object value, Object keyValue) {
		
		return UniqueValidate(beanClass,field,value,keyValue);
		
	}
	
	/**
	 * 对指定表的某个字段做唯一性验证
	 * @param className 需要检查的对象的ClassName
	 * @param field 需要检查的字段名称
	 * @param value 需要检查的字段的值
	 * @param keyValue 需要验证的记录的主键值
	 * @return 成功返回true否则返回false
	 */
	public static boolean UniqueValidate(String className, String field,
			Object value, Object keyValue) {
		boolean unique = true;
		String sql = "";
		AbstractBean bean = null;
		String primaryKey = "";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			con = BaseConnectionManage.getAvailableConnection();
			bean = (AbstractBean) Class.forName(className).newInstance();
			if ((keyValue == null) || ("".equals(keyValue))) {
				keyValue = Integer.valueOf(-1);
			}

			primaryKey = bean.PrimaryKey;
			sql = " select " + primaryKey + " from " + bean.TABLE_NAME
					+ " where " + field + "=?";
			pst = con.prepareStatement(sql);
			pst.setObject(1, value);

			rs = pst.executeQuery();
			if (rs.next()) {
				Object key = rs.getObject(primaryKey);
				if ((key != null)
						&& (!(key.toString().equals(keyValue.toString())))) {
					unique = false;
				}
			}
			BaseConnectionManage.FreeConnection(con);
			// if ((con != null) && (!(con.isClosed()))) con.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return unique;
	}
	
	/**
	 * 把一个字符串反序列化为对应的AbstractBean对象
	 * @param serializable 带有对象信息的序列化字符串
	 * @return AbstractBean对象
	 */
	public static AbstractBean Derializable(String serializable) {
		AbstractBean bean = null;
		ByteArrayInputStream byteArrayInputStream = null;
		ObjectInputStream objectInputStream = null;
		try {
			String redStr = java.net.URLDecoder.decode(serializable, "UTF-8");
			byteArrayInputStream = new ByteArrayInputStream(
					redStr.getBytes("ISO-8859-1"));
			objectInputStream = new ObjectInputStream(byteArrayInputStream);
			bean = (AbstractBean) objectInputStream.readObject();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		try {
			objectInputStream.close();
			byteArrayInputStream.close();
		} catch (Exception e) {
		}

		return bean;
	}
	
		
}

